<template>
  <div class="container">
    <!-- 表格部分 -->
    <div class="table-card">
      <div class="card-header">
        <h2>数据统计表格</h2>
        <div class="table-controls">
          <!-- 类别筛选下拉框 -->
          <select v-model="selectedCategory" @change="handleCategoryChange" class="category-filter">
            <option value="">全部类别</option>
            <option v-for="category in uniqueCategories" :key="category" :value="category">
              {{ category }}
            </option>
          </select>
          
          <!-- 导出按钮 -->
          <button @click="exportToExcel" class="export-btn">
            <i class="export-icon"></i> 导出数据
          </button>
        </div>
      </div>
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>序号</th>
              <th>类别</th>
              <th>当年累计量</th>
              <th>数据归属时间</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="(item, index) in filteredTableData" 
              :key="item.id"
              @click="handleRowClick(item)"
              :class="{ 'active-row': selectedItem && selectedItem.id === item.id }"
            >
              <td>{{ index + 1 }}</td>
              <td>{{ item.category }}</td>
              <td>{{ item.accumulated.toLocaleString() }}</td>
              <td>{{ item.dataTime }}</td>
              <td>{{ item.remark }}</td>
            </tr>
            <tr v-if="filteredTableData.length === 0">
              <td colspan="5" class="no-data">没有找到匹配的数据</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分割线 -->
    <div class="divider">
      <div class="divider-line"></div>
      <div class="divider-line"></div>
    </div>

    <!-- 图表部分 -->
    <div class="chart-card">
      <div class="card-header">
        <h2>{{ chartConfig.cardTitle }}</h2>
      </div>
      <div class="chart-container">
        <div id="chart" ref="chartRef"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import * as XLSX from 'xlsx';
import http from '@/api/http';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      // 表格数据 - 修复了重复的id问题
      tableData: [
        {
          id: 1,
          category: '产品A',
          accumulated: 1250,
          remark: '销量稳步增长',
          dataTime: '2023-06',
          monthlyData: [120, 150, 130, 140, 160, 180, 170, 190, 210, 230, 250, 280]
        },
        {
          id: 2,
          category: '产品B',
          accumulated: 860,
          remark: '季度波动较大',
          dataTime: '2023-06',
          monthlyData: [80, 70, 90, 60, 80, 100, 90, 70, 85, 95, 105, 115]
        },
        {
          id: 3,
          category: '产品C',
          accumulated: 520,
          remark: '新上市产品',
          dataTime: '2023-06',
          monthlyData: [0, 0, 30, 40, 50, 60, 70, 80, 85, 90, 95, 100]
        },
        {
          id: 4,
          category: '产品D',
          accumulated: 980,
          remark: '持续热销',
          dataTime: '2023-06',
          monthlyData: [90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 150]
        },
        {
          id: 5,
          category: '产品A',
          accumulated: 1380,
          remark: '销量持续增长',
          dataTime: '2023-07',
          monthlyData: [130, 160, 140, 150, 170, 190, 180, 200, 220, 240, 260, 290]
        },
        {
          id: 6,
          category: '产品B',
          accumulated: 920,
          remark: '市场需求上升',
          dataTime: '2023-07',
          monthlyData: [90, 80, 100, 70, 90, 110, 100, 80, 95, 105, 115, 125]
        },
        {
          id: 7,
          category: '产品B',
          accumulated: 920,
          remark: '市场需求上升',
          dataTime: '2023-07',
          monthlyData: [90, 80, 100, 70, 90, 110, 100, 80, 95, 105, 115, 125]
        },
        {
          id: 8,
          category: '产品B',
          accumulated: 920,
          remark: '市场需求上升',
          dataTime: '2023-07',
          monthlyData: [90, 80, 100, 70, 90, 110, 100, 80, 95, 105, 115, 125]
        }
      ],
      // 选中的行数据
      selectedItem: null,
      // 图表实例
      chartInstance: null,
      // 选中的筛选类别
      selectedCategory: '',
      // 图表配置参数
      chartConfig: {
        cardTitle: '数据趋势图表',
        title: '请选择一个类别查看详情',
        xAxis: {
          name: 'X轴',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
          name: '数值'
        },
        series: {
          name: ''
        },
        color: '#165DFF'
      },
      result_data_api:null,
      current_x:null,
      current_y:null,
    };
  },
  computed: {
    // 获取所有唯一的类别
    uniqueCategories() {
      const categories = new Set();
      this.tableData.forEach(item => {
        categories.add(item.category);
      });
      return Array.from(categories);
    },
    
    // 根据筛选条件过滤表格数据
    filteredTableData() {
      if (!this.selectedCategory || this.selectedCategory.trim() === '') {
        return [...this.tableData];
      }
      return this.tableData.filter(item => item.category === this.selectedCategory);
    },
    
    // 获取选中项的月度数据
    chartData() {
      console.log("选中的条目",this.selectedItem)
      if (this.selectedItem) {
        return this.selectedItem.monthlyData;
      }
      return this.filteredTableData.length > 0 ? this.filteredTableData[0].monthlyData : [];
    },
    
    // 图表标题
    displayTitle() {
      return this.selectedItem ? 
        `${this.selectedItem.category} ${this.selectedItem.remark}趋势` : 
        this.chartConfig.title;
    }
  },
  mounted() {
    // 初始化图表
    this.initChart();
    
    // 默认选中筛选后数据的第一项
    if (this.filteredTableData.length > 0) {
      this.selectedItem = this.filteredTableData[0];
    }
    // 页面加载完成后调用后端数据获取方法
    this.get_data_from_db();
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize);
  },
  // 组件销毁前清理资源
  beforeUnmount() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
    
    // 销毁ECharts实例
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
  },
  methods: {    
    get_data_from_db(){
        console.log("开始获取后端数据")
        try {
            // 显示加载状态
            // const loadingInstance = ElMessage.loading({
            //   message: '数据加载中...',
            //   duration: 0
            // });
            
            // 实际项目中替换为真实的API地址                 
            http.get('api/wsz_shebei/base_data_search', {})
                .then((result_) => {
                console.log("获取数据成功", result_);
                
                this.result_data_api = result_["find_data_detail"]
                var result = this.calculateDataSum(result_);
                console.log("???",result)
                // for(let i=0;i<data_detail.length;i++){
                //   result.push(
                //     {
                //       id: i+1,
                //       category: data_detail[i]["data_name"],
                //       accumulated: data_detail[i]["data_name"],
                //       remark: data_detail[i]["device_name"],
                //       dataTime: '2023-07',
                //       monthlyData: [90, 80, 100, 70, 90, 110, 100, 80, 95, 105, 115, 125]
                //     }
                //   )
                // }
                
                // 关键：判断处理后的数据是否有效，直接赋值给tableData
                if (result && Array.isArray(result) && result.length > 0) {
                  this.tableData = result; // 用处理后的result替换表格原始数据

                  // 更新选中项为新筛选数据的第一项（保持图表联动）
                  if (this.filteredTableData.length > 0) {
                    this.selectedItem = this.filteredTableData[0];
                    this.updateChart(); // 同步更新图表数据
                  }
                } else {
                  console.warn("处理后的数据为空，使用默认表格数据");
                  // 可选：数据为空时清空表格
                  // this.tableData = [];
                  // this.selectedItem = null;
                  // this.updateChart();
                }

                // 关闭加载状态（如需启用，可取消注释）
                // loadingInstance.close();
              })
              .catch((error) => {
                console.error("获取后端数据失败", error);
                // 关闭加载状态（如需启用，可取消注释）
                // loadingInstance.close();
                // ElMessage.error('获取数据失败，请稍后重试');                             
              });
          } catch (error) {
            console.error('获取数据过程异常：', error);
            // ElMessage.error('获取数据异常，请稍后重试');
          }
    },
    calculateDataSum(originalData) {
      const dataList = originalData.find_data_detail;
      // 用「device_name-data_name」作为组合键，确保同设备不同数据名分开分组
      const sumMap = {};

      // 分组累加逻辑：按device_name和data_name的组合分组
      dataList.forEach(item => {
        const deviceName = item.device_name;
        const dataName = item.data_name; // 新增data_name作为分组依据
        const dataValue = Number(item.data_detail);
        // 组合键：用「设备名-数据名」作为唯一标识
        const key = `${deviceName}-${dataName}`;
        
        // 累加当前组合键的数据
        sumMap[key] = (sumMap[key] || 0) + dataValue;
      });

      // 转换为目标数组并处理字段
      const result = Object.entries(sumMap).map(([key, data_sum], index) => {
        // 从组合键中拆分出device_name和data_name
        const [device_name, data_name] = key.split('-');
        return {
          id: index + 1, // 顺序索引（从1开始）
          category: device_name,
          remark: data_name, // 新增data_name字段，明确数据类型
          accumulated: data_sum.toFixed(2), // 累加总和（保留2位小数）
          dataTime: "2025-08",
          monthlyData: []
        };
      });

      return result;
    },
    // 初始化ECharts图表
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chartRef);
      this.updateChart();
    },
    
    // 更新图表数据
    updateChart() {
      if (!this.chartInstance) return;
      
      const option = {
        color: [this.chartConfig.color],
        title: {
          text: this.displayTitle,
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: '{b}: {c}'
        },
        legend: {
          data: [this.chartConfig.series.name],
          bottom: 10,
          textStyle: {
            color: '#666'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          name: this.chartConfig.xAxis.name,
          data: this.chartConfig.xAxis.data,
          axisLine: {
            lineStyle: {
              color: '#eee'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          name: this.chartConfig.yAxis.name,
          nameTextStyle: {
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#eee'
            }
          },
          axisLabel: {
            color: '#666',
            formatter: '{value}'
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        series: [
          {
            name: this.chartConfig.series.name,
            type: 'line',
            data: this.chartData,
            smooth: true,
            lineStyle: {
              width: 3
            },
            label:{
              show: true,
              trigger: 'item',
              position: 'right',
              formatter: '{c}',
              distance: 5
            },
            itemStyle: {
              radius: 6,
              borderColor: '#fff',
              borderWidth: 2
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: `rgba(${this.hexToRgb(this.chartConfig.color)}, 0.3)` },
                { offset: 1, color: `rgba(${this.hexToRgb(this.chartConfig.color)}, 0)` }
              ])
            }
          }
        ]
      };
      
      this.chartInstance.setOption(option);
    },
    
    // 处理表格行点击事件
    handleRowClick(item) {
      this.selectedItem = item;
      console.log("item",item,this.result_data_api)
      console.log("点击事件····",this.selectedItem)
      var x_zhou = []
      var y_zhou = []
      for(let i=0;i<this.result_data_api.length;i++){
        if(this.result_data_api[i]["device_name"] == item["category"] && this.result_data_api[i]["data_name"] == item["remark"]){
          x_zhou.push(this.result_data_api[i]["intime"])
          y_zhou.push(this.result_data_api[i]["data_detail"])
        }
      }
      this.selectedItem.monthlyData = y_zhou
      this.chartConfig.xAxis.data = x_zhou
      this.chartConfig.xAxis.data = x_zhou
      this.updateChart();
    },
    
    // 处理窗口大小变化
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    
    // 辅助方法：将十六进制颜色转换为RGB
    hexToRgb(hex) {
      const r = parseInt(hex.slice(1, 3), 16);
      const g = parseInt(hex.slice(3, 5), 16);
      const b = parseInt(hex.slice(5, 7), 16);
      return `${r}, ${g}, ${b}`;
    },
    
    // 处理类别筛选变化
    handleCategoryChange() {
      // 筛选变化后，重置选中项为筛选结果的第一项
      if (this.filteredTableData.length > 0) {
        this.selectedItem = this.filteredTableData[0];
      } else {
        this.selectedItem = null;
      }
      this.updateChart(); // 确保图表也更新
    },
    
    // 导出数据到Excel
    exportToExcel() {
      const exportData = this.filteredTableData.map((item, index) => ({
        '序号': index + 1,
        '类别': item.category,
        '当年累计量': item.accumulated,
        '数据归属时间': item.dataTime,
        '备注': item.remark
      }));
      
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '数据统计');
      
      const date = new Date();
      const fileName = `数据统计_${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}.xlsx`;
      
      XLSX.writeFile(workbook, fileName);
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  gap: 20px;
  background-color: #f9fafb;
  overflow: hidden;
}

.table-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: box-shadow 0.3s ease;
  height: 50%;
  display: flex;
  flex-direction: column;
}

.chart-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: box-shadow 0.3s ease;
  height: 50%;
  display: flex;
  flex-direction: column;
}

.table-card:hover, .chart-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.card-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #1d2129;
  font-weight: 600;
}

.table-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.category-filter {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  cursor: pointer;
  transition: border-color 0.2s;
}

.category-filter:focus {
  outline: none;
  border-color: #165DFF;
}

.export-btn {
  padding: 6px 16px;
  background-color: #165DFF;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background-color 0.2s;
}

.export-btn:hover {
  background-color: #0E42D2;
}

.export-icon::before {
  content: "📤";
}

.table-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.table-container::-webkit-scrollbar {
  width: 6px;
}

.table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.table-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.data-table th,
.data-table td {
  padding: 14px 20px;
  box-sizing: border-box;
  white-space: nowrap;
}

.data-table th {
  background-color: #f7f8fa;
  font-weight: 600;
  color: #4e5969;
  font-size: 14px;
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 1px solid #e5e6eb;
}

.data-table tbody tr {
  transition: all 0.2s ease;
  border-bottom: 1px solid #f2f3f5;
}

.data-table tbody tr:hover {
  background-color: #f7faff;
  cursor: pointer;
}

.data-table .active-row {
  background-color: #e8f3ff;
  border-left: 3px solid #165DFF;
}

.data-table td {
  color: #1d2129;
  font-size: 14px;
}

.data-table td:nth-child(3) {
  color: #165DFF;
  font-weight: 500;
}

.no-data {
  text-align: center;
  padding: 30px;
  color: #86909c;
  background-color: #fafafa;
}

.divider {
  display: flex;
  align-items: center;
  margin: 3px 0;
}

.divider-line {
  flex: 1;
  height: 1px;
  background-color: #e5e6eb;
}

.divider-text {
  padding: 0 5px;
  font-size: 10px;
  color: #86909c;
  white-space: nowrap;
}

.chart-container {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
}

#chart {
  width: 100%;
  height: 100%;
}

@media (max-width: 768px) {
  .container {
    padding: 10px;
    gap: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 12px 15px;
  }
  
  .table-controls {
    width: 100%;
    justify-content: space-between;
  }
  
  .data-table th,
  .data-table td {
    padding: 10px 8px;
    font-size: 12px;
  }
  
  .card-header h2 {
    font-size: 16px;
  }
  
  .divider-text {
    padding: 0 10px;
    font-size: 12px;
  }
  
  .export-btn, .category-filter {
    font-size: 12px;
    padding: 4px 8px;
  }
}
</style>
